package com.zw.pdm.module.system.controller;

import com.zw.pdm.base.BaseController;
import com.zw.pdm.common.JsonResult;
import com.zw.pdm.common.ValidResult;
import com.zw.pdm.entity.basic.Dept;
import com.zw.pdm.entity.basic.Org;
import com.zw.pdm.entity.sys.Role;
import com.zw.pdm.entity.sys.User;
import com.zw.pdm.module.basic.service.OrgService;
import com.zw.pdm.module.system.service.DeptService;
import com.zw.pdm.module.system.service.RoleService;
import com.zw.pdm.module.system.service.UserService;
import com.zw.pdm.util.FileUtils;
import com.zw.pdm.util.ShiroUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @Description: 帐户接口
 *
 * 权限：
 * system:user:view 查看
 * system:user:edit 编辑
 *
 * @Author: China.sgl
 * @Date: 2019/9/16 09:11
 */
@Controller
@RequestMapping("/sys/user")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private OrgService orgService;
    @Autowired
    private DeptService deptService;


    @Value("${user.upload.path}")
    private String uploadPath;

    @GetMapping
    @RequiresPermissions({"system:user:view"})
    public String page() {
        return "system/user/page";
    }

    /**
     * 用户列表
     *
     * @param user 查询条件封装
     * @return json
     */
    @ResponseBody
    @PostMapping("/list")
    @RequiresPermissions({"system:user:view"})
    public JsonResult userList(User user) {
        startPage();
        List<User> list = userService.findUsers(user);
        return jsonResult(list);
    }

    /**
     * 查询所有部门
     *
     * @return json数据
     */
    @GetMapping("/depts")
    @ResponseBody
    @RequiresPermissions({"system:user:view"})
    public List<Dept> depts() {
        return deptService.findDeptByCondition(new Dept());
    }

    /**
     * 查询所有部门
     *
     * @return json数据
     */
    @GetMapping("/orgs")
    @ResponseBody
    @RequiresPermissions({"system:user:view"})
    public List<Org> orgs() {
        return orgService.findOrgByCondition(new Org());
    }

    /**
     * 查询所有角色
     *
     * @return json数据
     */
    @GetMapping("/roles")
    @ResponseBody
    @RequiresPermissions({"system:user:view"})
    public List<Role> roles() {
        return roleService.findRoleByCondition(new Role());
    }

    /**
     * 检查帐号是否存在
     *
     * @param account 帐号
     * @return json 数据
     */
    @ResponseBody
    @PostMapping("/checkUnique")
    @RequiresPermissions({"system:user:view"})
    public ValidResult checkUnique(String account) {
        User user = userService.findUserByAccount(account);
        return ValidResult.result(user);
    }

    /**
     * 创建用户
     *
     * @param user    用户信息
     * @param roleIds 选中角色 id 数组
     * @param orgId 选中部门 id
     * @return json 数据
     */
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions({"system:user:edit"})
    public JsonResult save(User user, Integer[] roleIds, Integer orgId, Integer deptId) {
        return isNotNull(userService.saveUser(user, roleIds, orgId, deptId));
    }

    /**
     * 查询所有部门，标识用户拥有部门
     *
     * @param id 用户 id
     * @return json 数据
     */
    @GetMapping("/depts/{id}")
    @ResponseBody
    @RequiresPermissions({"system:user:view"})
    public List<Dept> depts(@PathVariable Integer id) {
        return deptService.findDeptCheckedByUserId(id);
    }

    /**
     * 查询所有部门，标识用户拥有部门
     *
     * @param id 用户 id
     * @return json 数据
     */
    @GetMapping("/orgs/{id}")
    @ResponseBody
    @RequiresPermissions({"system:user:view"})
    public List<Org> orgs(@PathVariable Integer id) {
        return orgService.findOrgCheckedByUserId(id);
    }

    /**
     * 查询所有角色，标识用户拥有角色
     *
     * @param id 用户 id
     * @return json 数据
     */
    @GetMapping("/roles/{id}")
    @ResponseBody
    @RequiresPermissions({"system:user:view"})
    public List<Role> roles(@PathVariable Integer id) {
        return roleService.findRoleCheckedByUserId(id);
    }

    /**
     * 修改用户与角色
     *
     * @param user    用户信息
     * @param roleIds 选中角色 id 数组
     * @param orgId 选中部门 id
     * @return json 数据
     */
    @ResponseBody
    @PostMapping("/edit")
    @RequiresPermissions({"system:user:edit"})
    public JsonResult update(User user, Integer[] roleIds, Integer orgId, Integer deptId) {
        return isNotNull(userService.updateUser(user, roleIds, orgId, deptId));
    }

    /**
     * 修改用户
     *
     * @param user 用户信息
     * @return json数数
     */
    @ResponseBody
    @PostMapping("/update")
    @RequiresPermissions({"system:user:edit"})
    public JsonResult update(User user) {
        return isNotNull(userService.updateUser(user));
    }

    /**
     * 重置用户密码
     *
     * @param id 用户 id
     * @return json数据
     */
    @ResponseBody
    @PostMapping("/reset")
    @RequiresPermissions({"system:user:edit"})
    public JsonResult resetPassword(Integer id) {
        return isNotNull(userService.resetPassword(id));
    }

    /**
     * 修改头像
     */
    @ResponseBody
    @PostMapping("/edit/img")
    public JsonResult updateImage(String imageData) {
        String imgName = UUID.randomUUID().toString() + ".png";
        User user = ShiroUtils.getUser();
        try {
            FileUtils.decodeBase64DataUrlToImage(imageData, uploadPath, imgName);
            FileUtils.remove(uploadPath+user.getAvatar());
            user = userService.updateAvatar("/files/" + imgName);
        } catch (IOException e) {
            return JsonResult.fail("修改头像失败！");
        }
        return JsonResult.success("修改头像成功！", user.getAvatar());
    }

    /**
     * 查询用户
     *
     * @param id 用户id
     * @return 用户
     */
    @ResponseBody
    @PostMapping("/id")
    @RequiresPermissions({"system:user:view"})
    public User id(Integer id) {
        return userService.findUserById(id);
    }

}
